package controller

import (
	"context"
	"fmt"
	"github.com/cy77cc/hioshop/global"
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/cy77cc/hioshop/utils/upload"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UploadHandler struct{}

func (UploadHandler) UploadAvatar(ctx *gin.Context) {
	res := utils.NewResponse()
	id, exists := ctx.Get("id")
	if !exists {
		res.SetRes(1, "查询不到id", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	qiniu := upload.Qiniu{}

	userId := id.(uint)
	file, err := ctx.FormFile("upload_file")
	_, s, err := qiniu.UploadFile(file)
	filePath := "http://ssu8fho4l.hn-bkt.clouddn.com/" + s
	// newUUID, _ := uuid.NewUUID()
	// relativePath := path.Join("/static/upload/avatar/", newUUID.String()+".jpg")
	// filePath := path.Join("/app", relativePath)
	// err = ctx.SaveUploadedFile(file, filePath)
	if err != nil {
		res.SetRes(1, "设置头像错误", err)
		ctx.JSON(http.StatusInternalServerError, res)
		return
	}
	user := models.User{}
	user.ID = userId
	user.Avatar = filePath
	err = user.UpdateUserInfo()
	if err != nil {
		res.SetRes(1, "设置头像错误", err)
		ctx.JSON(http.StatusInternalServerError, res)
		return
	}
	res.SetRes(1, "success", map[string]any{
		"fileUrl": filePath,
	})

	get := global.REDIS.HGet(context.Background(), fmt.Sprintf("user:%d", userId), "avatar")
	if get.String() != "" {
		global.REDIS.HSet(context.Background(), fmt.Sprintf("user:%d", userId), "avatar", filePath)
	}

	ctx.JSON(http.StatusOK, res)
}
